package com.jckl.foodathon.services.config;

import java.io.IOException;

import org.restlet.ext.jackson.JacksonRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.ClientResource;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.jckl.foodathon.common.constant.ApplicationConstants;
import com.jckl.foodathon.common.constant.CommunicationConstants;
import com.jckl.foodathon.model.Brand;
import com.jckl.foodathon.model.Response;

public class NewBrandConfiguration {
	
	public void perform(Activity activity, Brand brand){

		PerformNewBrandAsync async = new PerformNewBrandAsync(activity, brand);
		async.execute();
	}
	
	private class PerformNewBrandAsync extends AsyncTask<Void, Void, Boolean> {
		
		Activity activity;
		Context context;
		Brand brand;
		Response response;
		
		public PerformNewBrandAsync(Activity activity, Brand brand){
			this.activity = activity;
			this.context = activity.getApplicationContext();
			this.brand = brand;
		}
		
		
		@Override
		protected void onPreExecute() {
			
		}
		
		@Override
		protected Boolean doInBackground(Void... nothing) {
			
			boolean responseSuccess = false;
			
			try {
				Gson gson = new Gson();
				Log.i(CommunicationConstants.APP_TAG, "Brand JSON: "+gson.toJson(brand));
				
				ClientResource cr = new ClientResource(CommunicationConstants.SERVER_URI + CommunicationConstants.DATA_BRAND);
				JacksonRepresentation<Brand> brandJson = new JacksonRepresentation<Brand>(brand);
				Representation rep = cr.post(brandJson);
			
				String responseStatus = rep.getText();
				response = gson.fromJson(responseStatus, Response.class);
				
				if(response.getServerResponse() == ApplicationConstants.SERVER_RESP_SUCCESS)
					responseSuccess = true;	
				
			} catch (IOException IOex) {
				Log.e(CommunicationConstants.APP_TAG, "Unable to parse return value");
				IOex.printStackTrace();
			} catch (Exception ex){
				ex.printStackTrace();
			}
			
			return responseSuccess;
		}
		
		@Override
		protected void onProgressUpdate(Void... nothing){
	    }

		
		@Override
		protected void onPostExecute(Boolean responseSuccess) {
			if(responseSuccess){
				Toast.makeText(context, "Success", Toast.LENGTH_SHORT).show();
				//Refresh the brand info into sqlite
				GetAllBrandInfo brandInfo = new GetAllBrandInfo();
				brandInfo.perform(activity);
				
			}else{
				Toast.makeText(context, "Error: "+response.getRemark(), Toast.LENGTH_SHORT).show();
			}
	    }
	}

}
